package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @Title: DishServiceImpl
 * @Author 张宇
 * @Package com.sky.service.impl
 * @Date 2025/9/29 15:50
 */


@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     *
     * @param dto
     */
    // 开启事务
    @Transactional
    public void addDish(DishDTO dto) {
        // 构造菜品基本信息,将其存入dish表中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        // 调用mapper保存
        dishMapper.insert(dish);

        // 构造菜品口味列表数据,将其存入dish_flavor表中
        List<DishFlavor> dishFlavorList = dto.getFlavors();
        if (dishFlavorList != null && dishFlavorList.size()>0) {
            dishFlavorList.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });

            log.info("口味数据:{}", dishFlavorList);

            // 存入表中
            dishFlavorMapper.insertBatch(dishFlavorList);
        }

        // 清理缓存
        String key = "dish_" + dto.getCategoryId();
        redisTemplate.delete(key);
        log.info("{}的缓存已经删除",key);

    }


    /**
     * 分页查询菜品列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {

        // 设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.list(dto);
        return new PageResult(page.getTotal(), page.getResult());

    }


    /**
     * 删除菜品
     *
     * @param ids
     */
    @Transactional  // 加上事务
    public void delete(List<Long> ids) {
        // 删除之前判断是否起售,起售中不允许删除
        ids.forEach(id -> {
                    Dish dish = dishMapper.selectById(id);
                    if (dish.getStatus() == StatusConstant.ENABLE) {
                        throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                    }
                }
        );

        // 判断菜品是否被套餐关联,关联了不允许删
        Integer count = setmealDishMapper.countByDishId(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        // 删除菜品基本信息dish表
        dishMapper.delete(ids);

        // 删除菜品口味列表信息dish_flavor
        dishFlavorMapper.delete(ids);

    }

    /**
     * 根据id回显菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //根据id查询菜品基本信息
        Dish dish = dishMapper.selectById(id);

        // 根据菜品id查询口味列表数据
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);

        // 构造DishVO对象并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }


    /**
     * 修改菜品
     *
     * @param dto
     */
    @Transactional
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);

        // 修改菜品的基本信息,dish表
        dishMapper.update(dish);

        // 修改口味列表信息,dish_flavor
        // 先全部删除之前的数据,然后重新插入数据
        List<Long> ids = new ArrayList<>();
        ids.add(dto.getId());
        dishFlavorMapper.delete(ids);


        // 进行新增
        // 可能没有数据
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            // 进行关联
            flavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.seleteByCategoryId(dish);
    }


    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listDish(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 修改菜品的状态
     * @param categoryId 菜品分类id
     * @param id 菜品id
     */
    @Override
    public void status(Long categoryId, Long id) {
        dishMapper.status(categoryId,id);

    }


}
